-- ngx.say("dy_up")

local dyuputils = require('dyup_utils')
local _log = dyuputils.dummyLog
-- local _log = dyuputils.log
local selectOneserver = dyuputils.selectOneServer

-- get / type
_log("ngx.var.request_uri=" .. ngx.var.request_uri)
_log("ngx.var.host=" .. ngx.var.host)

local typeName, newUri = string.match(ngx.var.request_uri, '/(.-)/(.*)')
-- _log("typeName=")
-- _log(typeName)
-- _log("newUri=")
-- _log(newUri)

-- if newUri then
--   newUri = '/' .. newUri
-- else
--   newUri = '/'
-- end
newUri = ngx.var.request_uri


local origMethod = ngx.req.get_method()
_log("origMethod=" .. origMethod)

local proxyMethod = ngx["HTTP_"..origMethod]
if not proxyMethod then _log("unsupport method " .. origMethod) return end
_log("proxyMethod=" .. proxyMethod)


-- ngx.say("typeName=" , typeName)
local targetServer = selectOneserver(typeName, servers)

-- error handling 503
if not targetServer then
  ngx.status = 503
  ngx.say("Service Unavailable")
  return
end

_log("targetServer="..targetServer)


-- /proxy/http://ip:port/xxx
local upUrl='/proxy/http://' .. targetServer .. newUri
-- upUrl =/proxy/http://127.0.0.1:6001/echo/foo
_log("upUrl =" .. upUrl)
ngx.req.read_body()
-- local resp = ngx.location.capture(upUrl)
local origHeader = ngx.req.get_headers()
local resp = ngx.location.capture(upUrl,{
  method = proxyMethod,
  headers = origHeader,
  body = body
})

-- error handling 503
if not resp then
  ngx.status = 503
  ngx.say("Service Unavailable")
  return
end

-- status, headers, body, 错误处理, 记录
ngx.status = resp.status
if resp.status >= 500 then
  dyuputils.changeState(targetServer, dyuputils.SERVER_STATE.ERROR)
  ngx.say("Service Unavailable")
  return
end

-- seem success
dyuputils.incSucc(targetServer)

_log('ngx.status:'.. resp.status)
for k,v in pairs(resp.header) do
  _log('header :' .. k .. v)
  if k ~= "Transfer-Encoding" and k ~= "Connection" then
    ngx.header[k] = v
  end
end
ngx.say(resp.body)

